<!--
 * @Des: 字典管理
 * @Author: jin_yc
 * @Date: 2019-11-08 10:21:45
 * @LastEditor: jin_yc
 * @LastEditTime: 2022-08-19 14:59:26
 -->

<template>
  <div class="dic-container">
    <drawer-layout>
      <template v-slot:left="{ setFolded }">
        <fks-query-page
          ref="table"
          v-loading="loading"
          :data="tableData"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[20, 50, 100]"
          highlight-current-row
          :page-size.sync="pageSize"
          :current-page.sync="currentPage"
          :total="total"
          :element-loading-text="LANG.LOADING"
          :table-name="
            tableFlag == 'systemDic'
              ? LANG.SYS_DICTIONARY
              : LANG.BUSINESS_DICTIONARY
          "
          @query="initData"
          @selection-change="handleSelect"
        >
          <template slot="singleSearch">
            <div class="single-searchBox">
              <fks-input
                v-model="searchValue"
                size
                :placeholder="LANG.NAME_CODE"
                class="single-searchBox-item"
                clearable
                maxlength="50"
                @clear="search"
                @keyup.enter.native="search"
              >
                <fks-button
                  slot="append"
                  icon="fks-icon-search"
                  @click="search"
                />
              </fks-input>
              <fks-button
                v-if="
                  tableFlag == 'systemDic'
                    ? developerFlag
                    : nodePermission('businessDict:import', { types: [1] })
                "
                v-saas:dictionary="['main', 'notSaas']"
                @click="importModules"
              >
                <i class="fks-icon-import" />
                <span>{{ LANG.IMPORT }}</span>
              </fks-button>
              <fks-button
                v-if="
                  tableFlag == 'systemDic'
                    ? developerFlag
                    : nodePermission('businessDict:export', { types: [1] })
                "
                @click="exportData"
              >
                <i class="fks-icon-export" />
                <span>{{ LANG.EXPORT }}</span>
              </fks-button>
              <fks-button
                v-if="
                  tableFlag == 'systemDic'
                    ? developerFlag
                    : nodePermission('businessDict:add', { types: [1] })
                "
                v-saas:dictionary="['main', 'notSaas']"
                icon="fks-icon-plus"
                type="primary"
                @click="add"
              >
                <span>{{ LANG.ADD }}</span>
              </fks-button>
            </div>
          </template>
          <template>
            <fks-table-column
              type="selection"
              width="55"
            />
            <fks-table-column
              type="index"
              align="center"
              label="#"
            />
            <fks-table-column
              prop="code"
              :label="LANG.DICTIONARY_KEY"
              align="left"
              header-align="center"
              is-link
              min-width="120px"
            >
              <span
                slot-scope="scope"
                @click="
                  () => {
                    getDicDetail(scope)
                    setFolded(true)
                  }
                "
              >
                {{ scope.row.code }}
              </span>
            </fks-table-column>
            <fks-table-column
              prop="content"
              :label="LANG.DICTIONARY_NAME"
              align="left"
              header-align="center"
              min-width="120px"
            />
            <fks-table-column
              v-if="
                saasPermission(['main', 'notSaas'], 'dictionary') &&
                  (tableFlag == 'systemDic' ? developerFlag : true)
              "
              :label="LANG.OPERATION"
              class-name="table-opt-colunm"
              width="100"
              align="left"
            >
              <template slot-scope="scope">
                <fks-button
                  v-if="
                    tableFlag == 'systemDic'
                      ? developerFlag
                      : nodePermission('businessDict:edit', { types: [1] })
                  "
                  class="table-column-opt-button"
                  type="text"
                  @click="edit(scope.row)"
                >
                  {{ LANG.EDIT }}
                </fks-button>
                <fks-button
                  v-if="
                    tableFlag == 'systemDic'
                      ? developerFlag
                      : nodePermission('businessDict:delete', { types: [1] })
                  "
                  danger-text
                  @click="deleteRow(scope.row)"
                >
                  {{ LANG.DELETE }}
                </fks-button>
              </template>
            </fks-table-column>
          </template>
        </fks-query-page>
      </template>
      <template #right>
        <div class="dic-detail-box">
          <fks-query-page
            v-loading="detailLoading"
            :data="detailTableData"
            :element-loading-text="LANG.LOADING"
            :table-name="
              dictName
                ? `${dictName} - ${LANG.DICTIONARY_DETAIL}`
                : LANG.DICTIONARY_DETAIL
            "
            row-key="id"
            :page="false"
            default-expand-all
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          >
            <template slot="singleSearch">
              <div class="single-searchBox">
                <span v-saas:dictionary="['main', 'notSaas']">
                  <fks-button
                    v-if="
                      tableFlag == 'systemDic'
                        ? developerFlag
                        : nodePermission('businessDict:import', {
                          types: [1]
                        })
                    "
                    @click="importDetail"
                  >
                    <i class="fks-icon-import" />
                    <span>{{ LANG.IMPORT }}</span>
                  </fks-button>
                  <fks-button
                    v-if="
                      tableFlag == 'systemDic'
                        ? developerFlag
                        : nodePermission('businessDictDeatil:add', {
                          types: [1]
                        })
                    "
                    icon="fks-icon-plus"
                    type="primary"
                    @click="addDetail"
                  >
                    <span>{{ LANG.ADD }}</span>
                  </fks-button>
                </span>
              </div>
            </template>
            <template>
              <fks-table-column
                type="index"
                align="center"
                label="#"
                width="50"
              />
              <fks-table-column
                :label="LANG.DICCODE"
                align="left"
                header-align="center"
                min-width="120"
              >
                <template slot-scope="scope">
                  {{ scope.row.content.code }}
                </template>
              </fks-table-column>
              <fks-table-column
                v-if="languages.length > 0"
                :render-header="langSelect"
                header-row-class-name="select-lang"
                align="left"
                header-align="center"
                min-width="120"
              >
                <template slot-scope="scope">
                  {{ scope.row.content.content }}
                </template>
              </fks-table-column>
              <fks-table-column
                v-if="languages.length == 0"
                :label="defaultLabel"
                align="left"
                header-align="center"
                min-width="120"
              >
                <template slot-scope="scope">
                  {{ scope.row.content.content }}
                </template>
              </fks-table-column>
              <fks-table-column
                v-if="
                  saasPermission(['main', 'notSaas'], 'dictionary') &&
                    (tableFlag == 'systemDic' ? developerFlag : true)
                "
                :label="LANG.OPERATION"
                align="left"
                width="200"
              >
                <template slot-scope="scope">
                  <fks-button
                    v-if="
                      tableFlag == 'systemDic'
                        ? developerFlag
                        : nodePermission('businessDictDeatil:addSubDetail', { types: [1] })
                    "
                    type="text"
                    @click="addSubDetail(scope.row)"
                  >
                    {{ LANG.ADD_SUBDIC }}
                  </fks-button>
                  <fks-button
                    v-if="
                      tableFlag == 'systemDic'
                        ? developerFlag
                        : nodePermission('businessDictDeatil:edit', { types: [1] })
                    "
                    type="text"
                    @click="editDetail(scope.row)"
                  >
                    {{ LANG.EDIT }}
                  </fks-button>
                  <fks-button
                    v-if="
                      tableFlag == 'systemDic'
                        ? developerFlag
                        : nodePermission('businessDictDeatil:delete', { types: [1] })
                    "
                    danger-text
                    @click="deleteRow(scope.row)"
                  >
                    {{ LANG.DELETE }}
                  </fks-button>
                </template>
              </fks-table-column>
            </template>
          </fks-query-page>
        </div>
      </template>
    </drawer-layout>
    <import-dic
      :import-visible.sync="importVisible"
      :dic-id="dictionaryId"
      :import-type="importType"
    />
    <dic-dialog
      :dialog-type="dialogType"
      :data.sync="dicData"
      :visible="dialogVisible"
      :table-flag="tableFlag"
      @close="dialogVisible = false"
    />
    <dic-detail
      :data="detailNode"
      :visible.sync="detailDialogVisible"
      :type="type"
      :table-flag="tableFlag"
    />
  </div>
</template>

<script>
import DicDialog from './DicDialog'
import DicDetail from './DicDetail'
import ImportDic from './ImportDic'
import {
  getDic,
  getDicDetail,
  deleteDic,
  getAllDicDetail,
  sort,
  exportDic
} from '../api'
import DrawerLayout from '@/components/DrawerLayout'
import { DEVELOPER_FLAG } from '@/store/Getter/getterTypes'
import { ENUM } from '@/store/State/stateTypes'
import { lang } from '@/modules/SysConfig/Lang/langClass.js'
import { exportFile } from '@/utils/file'
export default {
  name: 'DicTable',
  components: {
    DicDialog,
    DicDetail,
    DrawerLayout,
    ImportDic
  },
  props: {
    tableFlag: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      detailLoading: false,
      searchValue: '',
      dialogVisible: false,
      detailDialogVisible: false,
      dialogType: '',
      // detailTotal: 0,
      type: 'add',
      detailNode: {}, //新增字典详情的时候传递给组件的对象
      detailTableData: [],
      selectList: [],
      defaultLabel: '',
      currentPage: 1,
      id: '',
      dictionaryId: '', //当前字典id（左侧选中字典）
      dictName: '', //字典名称，右侧列表标题
      dicPathId: '', // 字典地址
      pathId: '', // 节点id
      sort: '',
      sortValue: '',
      pageSize: 20,
      total: 0,
      currentLang: '', //字典详情表表头中所选语种
      dicData: {},
      tableData: [],
      subParentId: '', //新增字典子节点时，保存父节点的id
      checkedList: [], //选中要导出数据列表
      importVisible: false,
      importType: ''
    }
  },
  computed: {
    lang() {
      return this.$lang
    },
    languages() {
      return this.$store.state[ENUM].languages || []
    },
    developerFlag() {
      return this.$store.getters[DEVELOPER_FLAG]
    }
  },
  watch: {
    dictName(val) {
      if (val && val.length > 20) {
        this.dictName = val.slice(0, 20) + '...'
      }
    },
    //监听语种切换
    currentLang(val) {
      this.detailLoading = true
      let data = {
        parentId: this.dictionaryId,
        langCode: val
      }
      this.getDicDetailData(data)
    },
    $lang(val) {
      if (this.languages.length > 0) {
        this.languages.forEach((item) => {
          if (item.code == val) {
            this.currentLang = item.code
            //this.selectList = []
            this.initData()
          }
        })
      }
    }
  },
  mounted() {
    lang.forEach((item) => {
      if (item.code === this.$lang) {
        this.defaultLabel = item.name
      }
    })
  },
  created() {
    this.initData()
  },
  methods: {
    //字典详情列表添加子节点
    addSubDetail(row) {
      this.pathId = row.content.pathId //储存父节点pathId
      this.subParentId = row.id //储存父节点parentId
      this.addDetail('addSub')
    },
    //字典详情数据排序后保存方法
    saveDetail() {
      sort(this.detailTableData)
        .then((res) => {
          if (res.status) {
            this.$message.success(this.LANG.CHANGE_SORT_SUCCESS)
          }
        })
        .catch(() => {})
    },
    langSelect(h, { column, $index }) {
      // 给表格添加包裹的div
      return h('div', {}, [
        // 添加el-select 标签
        h(
          'fks-select',
          {
            on: {
              input: (value) => {
                this.currentLang = value
              }
            },
            props: {
              value: this.currentLang, // 给el-select 设置值（也是相当于v-model）
              size: 'small',
              class: 'select-lang',
              style: {
                height: '25px',
                width: '110px',
                paddingLeft: '0px',
                paddingRight: '0px'
              }
            }
          },
          [
            //给当前 el-select 设置 el-option
            this.languages.map((item) => {
              return h('fks-option', {
                props: {
                  value: item.code,
                  label: item.name
                }
              })
            })
          ]
        )
      ])
    },
    //删除字典详情
    deleteRow(row) {
      this.$confirm(this.LANG.DELETE_CONFIRM, {
        title: this.LANG.TIPS,
        type: 'warning',
        confirmButtonText: this.LANG.DELETE,
        cancelButtonText: this.LANG.CANCEL,
        confirmButtonClass: 'fks-button--danger',
        deleteMode: true
      })
        .then(() => {
          //删除左侧列表 根节点
          deleteDic(row.id)
            .then((res) => {
              if (res.status) {
                // this.currentPage = 1
                if (row.content.hasOwnProperty('sort')) {
                  let data = {
                    parentId: this.dictionaryId,
                    langCode:
                      this.languages.length > 0 ? this.currentLang : this.$lang
                  }
                  this.getDicDetailData(data) //查询第一个字典详情
                } else {
                  if (!((this.total - 1) % this.pageSize)) {
                    this.currentPage--
                  }
                  this.initData()
                }
                this.$message.success(this.LANG.DELETE_SUCCESS)
              }
            })
            .catch(() => {})
        })
        .catch(() => {})
    },
    //打开新增字典详情弹窗
    addDetail(type) {
      this.detailDialogVisible = true
      this.type = 'add'
      let currentLangList = []
      //若所配置的国际化语种中，有当前表格头所选语种
      if (this.languages.length > 0) {
        currentLangList = this.languages.filter((item) => {
          return item.code == this.currentLang
        })
      }
      this.detailNode = {
        langName: currentLangList[0]?.langName,
        langCode: currentLangList[0]?.langCode,
        parentId: type == 'addSub' ? this.subParentId : this.dictionaryId,
        pathId: type == 'addSub' ? this.pathId : this.dicPathId,
        serviceType: this.tableFlag == 'systemDic' ? '0' : '1',
        dictionaryId: this.dictionaryId
        // detailTotal: this.detailTotal
      }
    },
    //打开编辑字典详情弹窗
    async editDetail(row) {
      let pId = []
      let langCode = ''
      let langName = ''
      this.detailDialogVisible = true
      this.type = 'edit'
      //编辑时获取所有翻译
      await getAllDicDetail({
        dictionaryId: row.id
      })
        .then((res) => {
          if (res.data.length > 0) {
            res.data.forEach((item) => {
              if (item.content) {
                row[item.langCode] = item.content
              }
              pId.push({ id: item.id, label: item.langCode })
            })
          }
          if (this.languages.length > 0) {
            this.languages.forEach((item) => {
              if (item.code == this.currentLang) {
                langCode = item.code
                langName = item.name
              }
            })
          }
          Object.assign(
            row,
            {
              langCode: this.languages.length > 0 ? langCode : this.$lang,
              langName: langName
            },
            {
              pId: pId,
              code: row.content.code,
              dictionaryId: this.dictionaryId,
              sort: row.content.sort
            }
          )
          this.detailNode = JSON.parse(JSON.stringify(row))
        })
        .catch(() => {})
    },
    //清空搜索值回调
    search() {
      this.currentPage = 1
      this.tableData = []
      this.initData()
    },
    getDicList(data) {
      getDic(data)
        .then((res) => {
          this.loading = false
          if (res.status) {
            this.loading = false
            //获取左侧根节点列表
            this.tableData = res.data.list
            this.total = res.data.total
            //如果左侧根节点列表有值，渲染第一个字典详情
            if (res.data.list[0]) {
              this.dictName = res.data.list[0]?.content //第一个字典名称赋值
              this.dictionaryId = res.data.list[0].id //第一个字典id赋值
              this.pathId = res.data.list[0].pathId //第一个字典pathId赋值
              this.dicPathId = this.pathId
              this.id = res.data.list[0].id
              let data = {
                parentId: this.dictionaryId,
                langCode:
                  this.languages.length > 0 ? this.currentLang : this.$lang
              }
              this.getDicDetailData(data) //查询第一个字典详情
            } else {
              this.detailLoading = false
            }
          } else {
            this.detailLoading = false
          }
        })
        .catch(() => {
          this.loading = false
          this.detailLoading = false
          this.tableData = []
        })
    },
    //点击字典名称获取字典下字典详情数据
    getDicDetail({ row }) {
      this.detailLoading = true
      this.dictionaryId = row.id
      this.pathId = row.pathId
      this.dicPathId = this.pathId
      this.dictName = row?.content
      let data = {
        parentId: row.id,
        langCode: this.languages.length > 0 ? this.currentLang : this.$lang
        // page: 1,
        // size: 99999
      }
      this.getDicDetailData(data)
    },
    //新增、编辑字典详情数据后更新字典详情列表
    updateDicDetail() {
      this.detailLoading = true
      let data = {
        parentId: this.dictionaryId,
        langCode: this.languages.length > 0 ? this.currentLang : this.$lang
      }
      this.getDicDetailData(data)
    },
    //获取字典详情数据
    getDicDetailData(data) {
      getDicDetail(data)
        .then((res) => {
          this.detailLoading = false
          if (res.status) {
            this.detailTableData = res.data ? res.data : []
          }
        })
        .catch(() => {
          this.detailTableData = []
          this.detailLoading = false
        })
    },
    //选择多选框
    handleSelect(val) {
      this.checkedList = []
      this.checkedList = val
    },
    //导出字典
    exportData() {
      if (!this.checkedList || !this.checkedList.length) {
        return this.$message.warning(this.LANG.EXPORT_REQUIRED)
      }
      exportDic(this.checkedList)
        .then((res) => {
          if (res.status) {
            this.$message.success(this.LANG.EXPORT_SUCCESS)
            exportFile(res)
            this.$refs.table.$children[0].clearSelection()
            this.checkedList = []
          }
        })
        .catch(() => {
          this.checkedList = []
          this.$refs.table.$children[0].clearSelection()
        })
    },
    //打开导入字典模块弹窗
    importModules() {
      this.importType = 'importModules'
      this.importVisible = true
    },
    //打开导入字典详情弹窗
    importDetail() {
      this.importType = 'importDetail'
      this.importVisible = true
    },
    //打开新增字典弹窗
    add() {
      this.dialogType = 'add'
      this.dicData = {
        langCode: this.$lang
      }
      this.dialogVisible = true
    },
    /**
     * @description: 编辑字典
     * @param {row} 被编辑行数据
     */
    edit(row) {
      this.dialogType = 'edit'
      this.dicData = {}
      getAllDicDetail({
        dictionaryId: row.id,
        langCode: ''
      })
        .then((res) => {
          if (res.data.length > 0) {
            res.data.forEach((item) => {
              if (item.content) {
                this.$set(this.dicData, item.langCode, item.content)
                this.$set(this.dicData, 'code', row.code)
                this.$set(this.dicData, 'id', row.id)
                this.$set(this.dicData, 'pathId', row.pathId)
                this.dialogVisible = true
              }
            })
          }
        })
        .catch(() => {})
      // this.dicData = Object.assign(row, {
      //   langCode: this.$lang
      // })
      this.dialogVisible = true
    },
    //初始化列表数据
    // @permission('businessDict:query')
    initData() {
      //加载左侧列表（根节点）,其中$lang为系统当前语种,currentLang为字典详情表表头中所选语种
      this.currentLang = this.$lang
      let data = {
        serviceType: this.tableFlag == 'systemDic' ? '0' : '1',
        langCode: this.currentLang,
        code: this.searchValue,
        page: this.currentPage,
        size: this.pageSize
      }
      this.loading = true
      this.getDicList(data)
    }
  }
}
</script>

<style lang="scss" scoped>
.dic-container {
  width: 100%;
  height: 100%;
  min-width: 498px;
  overflow-x: hidden;
  overflow-y: auto;
}
::v-deep .fks-table .fks-input--suffix .fks-input__inner {
  padding-left: 30px !important;
}

::v-deep .fks-table th > .cell .fks-input--small .fks-input__inner {
  border: none;
  text-align: center;
  background-color: transparent;
}

::v-deep .fks-select .fks-input .fks-select__caret {
  margin-top: -0.5px;
}

.dic-detail-box {
  height: 100%;
  background-color: #fff;
}
</style>